#include <iostream>
#include <fstream>
#include <string>
#include "GraphExporter.h"

using namespace std;

#define GRAPH_SIZE "800,600"
#define GRAPH_TITLE "IG/BG"
#define GRAPH_XLABEL "time"
#define GRAPH_YLABEL "value"
#define GNUPLOT_COMMAND "gnuplot"

GraphExporter::GraphExporter(double* bestValues, data* dataItems, string fileName)
{
	this->fileName = fileName;
	this->bestValues = bestValues;
	this->dataItems = dataItems;
}

GraphExporter::~GraphExporter()
{
}

void GraphExporter::createSVGFile()
{
	FILE *gnuplotOut;
	char buffer[256];
	string gnuPlotCommand;
	gnuPlotCommand = gnuPlotCommand + GNUPLOT_COMMAND + " " + "gnuplot.tmp";

	if (!(gnuplotOut = popen(gnuPlotCommand.c_str(), "r")))
	{
		cerr << "Cannot run gnuplot!" << endl;
		return;
	}

	while (fgets(buffer, sizeof(buffer), gnuplotOut) != NULL)
	{
		cout << buffer;
	}

	pclose(gnuplotOut);
}

void GraphExporter::exportSVG()
{

	double p = bestValues[0];
	double cg = bestValues[1];
	double c = bestValues[2];
	double dt = bestValues[3];
	double k = bestValues[4];

	FILE *f = fopen("gnuplot.tmp", "w");
	fprintf(f, "set terminal svg size %s dynamic enhanced fname 'arial' fsize 10 butt solid\n",	GRAPH_SIZE);
	fprintf(f, "set output \"%s.svg\"\n", fileName.c_str());
	fprintf(f, "set title \"p=%f, cg=%f, c=%f, dt=%f, k=%f\"\n", p, cg, c, dt, k);
	fprintf(f, "set grid\n");
	fprintf(f,"plot \"bg.tmp\" using 1:2 with lines ti \"Bg\","
		  	  "\"ig.tmp\" using 1:2 with lines ti \"Ig\", "
			  "\"ig_.tmp\" using 1:2 with lines ti \"newIg\"\n");
	fclose(f);

	f = fopen("bg.tmp", "w");

	for (int i = 0; i < dataItems->length; i++)
	{
		double y_bg = dataItems->items[i].bg;
		fprintf(f, "%d   %f\n", i, y_bg);
	}
	fclose(f);

	f = fopen("ig.tmp", "w");

	for (int i = 0; i < dataItems->length; i++)
	{
		double y_bg = dataItems->items[i].ig;
		fprintf(f, "%d   %f\n", i, y_bg);
	}
	fclose(f);

	f = fopen("ig_.tmp", "w");
	for (int i = 0; i < dataItems->length; i++)
	{
		double value = p*dataItems->items[i].bg + cg*dataItems->items[i].bg*(dataItems->items[i].bg - dataItems->items[i].ig)+c;
		fprintf(f, "%d   %f\n", i, value);
	}
	fclose(f);

	createSVGFile();

	remove("bg.tmp");
	remove("ig.tmp");
	remove("ig_.tmp");
}

